
#include"Common.hpp"
#include<iostream>
#include<cstring>
#include<string>
#include<cstdlib>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

using namespace std;

int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        cerr << "Usage: " << argv[0] << " localport" << std::endl;
        Die(USAGE_ERR);
    }
    string server_ip=argv[1];
    uint16_t server_port=stoi(argv[2]);

   // 1. 创建socket
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        cerr << "socket error" << endl;
        Die(SCOKET_ERR);
    }

    // 1.1 填充server信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = ::htons(server_port);
    server.sin_addr.s_addr = ::inet_addr(server_ip.c_str());

    while(true)
    {
        cout<<"请输入你要查询的单词   ";
        string message;
        getline(cin,message);
        int n=sendto(sockfd,message.c_str(),message.size(),0,Change(&server),sizeof(server));
        (void)n;

        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        n = ::recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, Change(&temp), &len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;

}